package com.huanxing.cloud.promotion.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.common.security.handler.HxBusinessException;
import com.huanxing.cloud.promotion.api.constant.MallEventConstants;
import com.huanxing.cloud.promotion.api.entity.CouponGoods;
import com.huanxing.cloud.promotion.api.entity.CouponInfo;
import com.huanxing.cloud.promotion.api.entity.CouponUser;
import com.huanxing.cloud.promotion.mapper.CouponInfoMapper;
import com.huanxing.cloud.promotion.mapper.CouponUserMapper;
import com.huanxing.cloud.promotion.service.ICouponGoodsService;
import com.huanxing.cloud.promotion.service.ICouponInfoService;
import com.huanxing.cloud.shop.api.remote.RemoteShopInfoService;
import com.huanxing.cloud.shop.api.vo.ShopInfoVO;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements ICouponInfoService {

	private final ICouponGoodsService couponGoodsService;

	@DubboReference
	private final RemoteShopInfoService remoteShopInfoService;

	private final CouponUserMapper couponUserMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean save(CouponInfo entity) {
		if (!super.save(entity)) {
			throw new HxBusinessException("保存失败");
		}
		if (MallEventConstants.USE_RANGE_2.equals(entity.getUseRange())) {
			List<CouponGoods> goodsList = entity.getCouponGoodsList();
			if (goodsList.isEmpty()) {
				throw new HxBusinessException("指定商品不能为空");
			}
			goodsList.forEach(couponGoods -> {
				couponGoods.setCouponId(entity.getId());
			});
			couponGoodsService.saveBatch(goodsList);
		}

		return Boolean.TRUE;
	}

	@Override
	public CouponInfo getCouponById(String id) {
		CouponInfo couponInfo = baseMapper.selectById(id);
		if (ObjectUtil.isNotNull(couponInfo) && MallEventConstants.USE_RANGE_2.equals(couponInfo.getUseRange())) {
			couponInfo.setCouponGoodsList(couponGoodsService.getByCouponId(couponInfo.getId()));
		}
		Map<String, List<ShopInfoVO>> stringListMap = getShopInfo(Collections.singletonList(couponInfo.getShopId()));
		couponInfo.setShopInfo(stringListMap.get(couponInfo.getShopId()).get(0));
		return couponInfo;
	}

	@Override
	public IPage<CouponInfo> getPage(Page page, CouponInfo couponInfo, CouponGoods couponGoods, CouponUser couponUser) {
		IPage<CouponInfo> iPage = baseMapper.selectCouponPage(page, couponInfo, couponGoods, couponUser);
		if (CollectionUtils.isEmpty(iPage.getRecords())) {
			return iPage;
		}
		// 从优惠券List中提取店铺ID
		List<String> shopIds = iPage.getRecords()
			.stream()
			.map(CouponInfo::getShopId)
			.distinct() // 去重，如果有可能有重复的
			.toList();
		Map<String, List<ShopInfoVO>> stringListMap = getShopInfo(shopIds);

		iPage.getRecords().forEach(v -> {
			List<ShopInfoVO> existShopList = stringListMap.get(v.getShopId());
			if (!CollectionUtils.isEmpty(existShopList)) {
				if (Objects.nonNull(couponUser.getUserId())) {
					// 查询领取数量
					Long count = couponUserMapper.selectCount(Wrappers.<CouponUser>lambdaQuery()
						.eq(CouponUser::getCouponId, v.getId())
						.eq(CouponUser::getUserId, couponUser.getUserId()));
					v.setUserReceiveCount(count);
				}
				v.setShopInfo(existShopList.get(0));
			}
		});
		return iPage;
	}

	@Override
	public IPage<CouponInfo> getAdminPage(Page page, CouponInfo couponInfo) {
		IPage<CouponInfo> iPage = this.page(page, Wrappers.lambdaQuery(couponInfo));
		if (CollectionUtils.isEmpty(iPage.getRecords())) {
			return iPage;
		}
		// 从优惠券List中提取店铺ID
		List<String> shopIds = iPage.getRecords()
			.stream()
			.map(CouponInfo::getShopId)
			.distinct() // 去重，如果有可能有重复的
			.toList();
		Map<String, List<ShopInfoVO>> stringListMap = getShopInfo(shopIds);

		iPage.getRecords().forEach(v -> {
			List<ShopInfoVO> existShopList = stringListMap.get(v.getShopId());
			if (!CollectionUtils.isEmpty(existShopList)) {
				v.setShopInfo(existShopList.get(0));
			}
		});
		return iPage;
	}

	private Map<String, List<ShopInfoVO>> getShopInfo(List<String> shopIds) {
		// 调用店铺服务，获取店铺详情
		List<ShopInfoVO> shopInfoVOList = remoteShopInfoService.getShopByIds(shopIds);
		if (CollectionUtils.isEmpty(shopInfoVOList)) {
			throw new IllegalArgumentException("query shop list fail!");
		}
		// 使用Stream流创建店铺ID到店铺对象的映射
		return shopInfoVOList.stream().collect(Collectors.groupingBy(ShopInfoVO::getShopId));
	}

}
